package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.ProductOrderSummaryQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.ProductOrderSummaryDao;
import cn.org.eshow.model.ProductOrderSummary;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("rechargeSummaryDao")
public class ProductOrderSummaryDaoHibernate extends GenericDaoHibernate<ProductOrderSummary, Integer> implements ProductOrderSummaryDao {

    public ProductOrderSummaryDaoHibernate() {
        super(ProductOrderSummary.class);
    }

    @Override
    public List<ProductOrderSummary> list(ProductOrderSummaryQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public Page<ProductOrderSummary> search(ProductOrderSummaryQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.pagesize);
        }
        return page(rule);
    }


    public EnhancedRule setRule(EnhancedRule rule, ProductOrderSummaryQuery query) {
        if (query != null) {
            rule.add(Restrictions.isNotNull("id"));
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (query.type != null) {
                rule.add(Restrictions.like("type", query.type, MatchMode.ANYWHERE));
            }
            if (query.year != null) {
                rule.add(Restrictions.eq("year", query.year));
            }
            if (query.month != null) {
                rule.add(Restrictions.eq("month", query.month));
            }
            if (query.week != null) {
                rule.add(Restrictions.eq("week", query.week));
            }
            if (query.day != null) {
                rule.add(Restrictions.eq("day", query.day));
            }
            if (query.getOrder() != null) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }
}
